import
os
import
numpy
as
np
import
matplotlib.pyplot
as
plt
from
sklearn.decomposition
import
PCA
from
sklearn.manifold
import
TSNE
from
tensorflow.keras.applications.mobilenet_v2
import
MobileNetV2, preprocess_input
from
tensorflow.keras.preprocessing
import
image
# Function to load and process images from a folder in batches
def
load_and_process_images(folder, batch_size=32):
filenames = os.listdir(folder)
features = []
model = MobileNetV2(weights='imagenet', include_top=False, pooling='avg', input_shape=(112, 1
for
i
in
range(0, len(filenames), batch_size):
batch_images = []
for
filename
in
filenames[i:i+batch_size]:
img_path = os.path.join(folder, filename)
img = image.load_img(img_path, target_size=(112, 112))
img_array = image.img_to_array(img)
batch_images.append(img_array)
batch_images_preprocessed = preprocess_input(np.array(batch_images))
batch_features = model.predict(batch_images_preprocessed)
features.extend(batch_features)
return
features
# Load and process images in batches
cats = load_and_process_images('Cat')
dogs = load_and_process_images('Dog')
all_features = np.array(cats + dogs)
# Convert to NumPy array
# Perform PCA and t-SNE
pca = PCA(n_components=2)
features_pca = pca.fit_transform(all_features)
tsne = TSNE(n_components=2, perplexity=30, n_iter=1000)
features_tsne = tsne.fit_transform(all_features)
# Visualize features using PCA and t-SNE
def
plot_features_2d(features, title):
plt.scatter(features[:len(cats), 0], features[:len(cats), 1], label='Cat', alpha=0.5)
plt.scatter(features[len(cats):, 0], features[len(cats):, 1], label='Dog', alpha=0.5)
plt.legend()
plt.title(title)
plt.show()
plot_features_2d(features_pca, 'PCA')
plot_features_2d(features_tsne, 't-SNE')